<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    //

    /**
     * 文件上传
     * @param Request $request
     */
    public function upload(Request $request)
    {

            $file = $request->file('file');

            //判断文件是否上传成功
            if($file->isValid()) {
                //原文件名
                $originaName = $file->getClientOriginalName();
                //扩展名
                $ext = $file->getClientOriginalExtension();
                //文件类型
                $type = $file->getClientMimeType();
                //临时文件绝对路径
                $realPath = $file->getRealPath();

                //路径拼接
                $pathName = date('Y-m-d') . '/' . uniqid() . '.' . $ext;

                //上传文件
                $bool = Storage::disk('uploads')->put($pathName, file_get_contents($realPath));

                if($bool){
                    $result = [
                        'code' => '1',
                        'content' => '上传成功',
                        'name' => $originaName,
                        'msg'=>'/uploads/'.$pathName,
                    ];
                }else{
                    $result = [
                        'code' => '0',
                        'content' => '上传失败',
                    ];
                }

                return $result;
            }

    }

    /**
     *删除图片
     */
    public function delFileUpload(Request $request)
    {
        if($request->isMethod('POST')){
            $data = $request->input();
            if(!empty($data['imgUrl'])){
                //删除文件
                if($data['key1']!=''){
                    $this->del_img($data['table'],$data['key2'],'','id',$data['key1']);
                }


                $bool = Storage::disk('uploads')->delete(str_replace('/uploads/','',$data['imgUrl']));

                if($bool){
                    $result = [
                        'code' => 1,
                        'content' => '删除成功',
                        'msg' => $bool,
                    ];
                }else{
                    $result = [
                        'code' => 0,
                        'content' => '文件已删除',
                    ];
                }
            }else{
                $result = [
                    'code' => 0,
                    'content' => '请重新删除，数据不存在',
                ];
            }

            return $result;
        }
    }

    /***
     * 清空图片字段
     * @param $table   表格
     * @param $field   修改的字段
     * @param $value   值
     * @param $id_field  根据id修改
     * @param $id_value   id值为好多
     * @return mixed
     */
    public function del_img($table,$field,$value,$id_field,$id_value)
    {
        return DB::update('update '.$table.' set '.$field.' ="" '.$value.'where '.$id_field.' = ?', [$id_value]);

    }

}
